<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 提示区域 -->
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 步骤条区域 -->
      <el-steps
        :space="200"
        finish-status="success"
        align-center
        :active="activeIndex - 0"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tab栏区域 -->

      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          :tab-position="'left'"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
          v-model="activeIndex"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                expand-trigger="hover"
                :options="cateList"
                :props="cateProps"
                v-model="addForm.goods_cat"
              >
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染表单的Item项 -->
            <!-- 父级 -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTableData"
              :key="item.attr_id"
            >
              <!-- 子级 -->
              <el-checkbox-group v-model="item.newValue">
                <el-checkbox
                  :label="cb"
                  v-for="(cb, i) in item.attr_vals"
                  :key="i"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTableData"
              :key="item.attr_id"
            >
              <!-- 子级 -->
              <el-checkbox-group v-model="item.newValue">
                <el-checkbox
                  :label="cb"
                  v-for="(cb, i) in item.attr_vals"
                  :key="i"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- el-upload商品图片上传
  action:指定图片上传api接口
  :on-preview ： 当点击图片时会触发该事件进行预览操作,处理图片预览
  :on-remove : 当用户点击图片右上角的X号时触发执行
  :on-success：当用户点击上传图片并成功上传时触发
  list-type ：设置预览图片的方式
  :headers ：设置上传图片的请求头 -->
            <el-upload
              list-type="picture"
              :action="uploadURL"
              :headers="headerObj"
              :on-success="successImage"
              :on-remove="removeImage"
              :on-preview="previewImg"
              multiple
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <!-- 添加商品的按钮 -->
            <el-button type="primary" class="btnAdd" @click="add"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
      <img :src="previewPath" alt="" class="previewImg" />
    </el-dialog>
  </div>
</template>

<script>
//思路- 0.布局-用到步骤条el-step组件,每个tab组件里套着表单组件。步骤条与tab如何联动？，可给tab声明1个激活索引v-model="activeIndex"同时每个tab子项给到name=“索引”，步骤条调用该索引   1.tab切换验证：切换下一个,得验证上一个是否选择？可用离开之前属性-:before-leave 调用方法，判断用户是否选择了下拉的3级列表  2.点击商品属性或商品参数面板，要根据上次选择的3级分类id请求对应数据。你怎么知道它点击的是商品属性，还是商品参数？点击时@tab-click="tabClicked"通过判断当前激活索引是多少，做相应的接口请求 4.提交必须的参数接口-看是否能提交进去

//点击图片上传-1.上传成功，会触发成功的事件，通过file文件里流信息，拿到临时路径，存到后台要求的字段里 2.图片删除-从file流协议里找到你要删除的那个临时路径，从提交的数组中splice切掉 3.预览功能-通过file文件里流获取后台返回的正式地址，写到图片src里

import { catelist, attrlist, addgoods } from "@/api/api.js"

export default {
  data() {
    return {
      activeIndex: "0",
      // 添加商品的表单数据对象
      addForm: {
        goods_name: "奎哥22",
        goods_price: 10,
        goods_weight: 10,
        goods_number: 10,
        // 商品所属的分类数组
        goods_cat: [52, 64, 74],
        // goods_cat: [],
        // 图片的数组
        pics: [], // {"pic":"/tmp_uploads/30f08d52c551ecb447277eae232304b8"},
        // 商品的详情描述
        goods_introduce: "",
        attrs: [], //attrs {"attr_id":15,"attr_value":"ddd"},
      },
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          //自定义正则-配合插件any-rule 别称铁皮
          // { pattern:/^[a-zA-Z0-9_-]{4,16}$/, message: '请输入正确的账号格式长度4到16位字母数字下划线开头', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
      },
      // 商品分类列表
      cateList: [],
      cateProps: {
        label: "cat_name",
        value: "cat_id",
        children: "children",
      },
      // 动态参数列表数据
      manyTableData: [],
      // 静态属性列表数据
      onlyTableData: [],
      // 上传图片的接口地址
      uploadURL: "http://127.0.0.1:8888/api/private/v1/upload",
      // uploadURL: "https://lianghj.top:8888/api/private/v1/upload",
      // 图片上传组件的headers请求头对象-拿token
      headerObj: {
        Authorization: localStorage.getItem("token"),
      },
      previewPath: "", //预览路径
      previewVisible: false,
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    allCheck(row) {
      console.log(222, row)
    },
    // 获取商品分类列表数据
    async getCateList() {
      const res = await catelist()
      if (res.meta.status === 200) {
        this.$message.success("获取分类列表成功")
        // 把数据列表，赋值给 catelist
        this.cateList = res.data
      }
    },
    //点击切换时进行验证
    async tabClicked() {
      //根据点击哪一个获取相应接口
      //获取动态参数接口  ({id:cateid,sel:'many'})
      // console.log(177,this.addForm.goods_cat);
      let cateId = this.addForm.goods_cat[2]
      console.log("点击的第几个", this.activeIndex)
      if (this.activeIndex == 1) {
        let res = await attrlist({ id: cateId, sel: "many" })
        //把数据字符串处理数组渲染
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals.split(",")
          //绑定老数据有问题-可以深拷贝
          item.newValue = JSON.parse(JSON.stringify(item.attr_vals))
        })
        this.manyTableData = res.data
      }
      if (this.activeIndex == 2) {
        let res = await attrlist({ id: cateId, sel: "only" })
        //把数据字符串处理数组渲染
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals.split(",")
          //绑定老数据有问题-可以深拷贝
          item.newValue = JSON.parse(JSON.stringify(item.attr_vals))
        })
        this.onlyTableData = res.data
      }
    },

    //判断用户从哪里离开，有没有选择级联菜单-要配置tab离开属性勾子:before-leave="beforeTabLeave"
    beforeTabLeave(newValue, oldValue) {
      // console.log(newValue, oldValue)
      if (oldValue == 0 && this.addForm.goods_cat.length != 3) {
        return false
      }
    },

    // 处理图片预览效果-1.从文件流里，拿到后台上传成功的那个正式地址
    previewImg(file) {
      console.log("点击的那个图片信息", file)
      let preURL = file.response.data.url //服务器上的地址
      this.previewPath = preURL
      this.previewVisible = true
    },

    // 处理移除图片的操作-1.从你上传成功的数组里移除掉
    removeImage(file) {
      console.log("点击的那个图片信息", file)
      //根据已知删除数据中某个值  点击的a  已有数据[1,2,a,b]  arr.findIndex(item=>{查找某个值}) 返回索引  splice(index,1)
      let delPath = file.response.data.tmp_path
      let index = this.addForm.pics.findIndex((item) => {
        item.pic == delPath
      })
      this.addForm.pics.splice(index, 1)
      console.log("删除后的数组中值", this.addForm.pics)
    },
    // 监听图片上传成功的事件-response[{pic:临时路径地址}]
    successImage(file) {
      //存储后端响应信息,删除时从数组里删除
      console.log("上传成功数据", file)
      let path = file.data.tmp_path
      this.addForm.pics.push({ pic: path })
      console.log("删除前的值", this.addForm.pics)
    },

    // 最后添加商品-先验证用户必选项有没有选择,根据文档提交数据
    add() {
      this.$refs["addFormRef"].validate(async (valid) => {
        //验证通过
        if (valid) {
          this.addForm.goods_cat = this.addForm.goods_cat.join(",")
          //对选择过的动态参数或静态属性进行处理,按照接口要求提交
          //动态参数
          this.manyTableData.forEach((item) => {
            // console.log(258,item.newValue);
            let onlyVal = {
              attr_id: item.attr_id,
              attr_value: item.newValue,
            }
            this.addForm.attrs.push(onlyVal)
          })
          //静态属性
          this.onlyTableData.forEach((item) => {
            // console.log(258,item.newValue);
            let onlyVal = {
              attr_id: item.attr_id,
              attr_value: item.newValue,
            }
            this.addForm.attrs.push(onlyVal)
          })

          let res = await addgoods(this.addForm)
          if (res.meta.status === 201) {
            this.$message.success(res.meta.msg)
            this.$router.push("/goods")
          }

          this.addForm.goods_cat = []
        } else {
          this.$message.error("请填写必要的商品信息")
          return false
        }
      })
    },
  },
  //计算属性
  computed: {
    // cateId() {
    //   if (this.addForm.goods_cat.length === 3) {
    //     return this.addForm.goods_cat[2]
    //   }
    //   return null
    // }
  },
}
</script>

<style lang="scss" scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}

.previewImg {
  width: 100%;
}

.btnAdd {
  margin-top: 15px;
}
//sass,less: 注意此处用/deep/进行样式穿透时,可能会报错，可用::v-deep
::v-deep .ql-editor {
  min-height: 300px;
}
</style>
